#coding=utf8

import os
import jinja2


def render(template, ctx):
    t = jinja2.Template(template)
    return t.render(**ctx)


class Template(object):
    def __init__(self, ctx):
        self.ctx = ctx

    def __call__(self, template, ctx=None):
        use = ctx
        if ctx is None:
            use = self.ctx

        return render(template, use)


def copy_dir(from_, to, ctx):
    T = Template(ctx)
    
    if not os.path.exists(T(to)):
        os.mkdir(T(to))

    for item in os.listdir(from_):
        item_path = os.path.join(from_, item)
        dst_path = os.path.join(to, item)

        if os.path.isdir(item_path):
            copy_dir(item_path, dst_path, ctx)
        else:
            copy_file(item_path, dst_path, ctx)

    
def copy_file(from_, to, ctx):
    T = Template(ctx)

    with open(from_, 'rb') as f:
        content = f.read()

    dst_file = T(to)
    if dst_file.endswith('.pyt'):
        dst_file = dst_file[:-1]

    with open(dst_file, 'wb') as f:
        f.write(T(content))
